package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.FilterAdapter;
import flc.ast.bean.FilterBean;
import flc.ast.databinding.ActivityVideoFilterBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.ToastUtil;

public class VideoFilterActivity extends BaseAc<ActivityVideoFilterBinding> {

    public static String videoPath;
    private FilterAdapter filterAdapter;
    private int oldPosition = 0;
    private String oldPath = "";
    private boolean isFilter = false;
    private String filter = "";
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoSbLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_filter;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoFilterBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivGenerate.setOnClickListener(this);
        mDataBinding.tvDeriveVideo.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivGenerate:
                if (TextUtils.isEmpty(filter)) {
                    isFilter = false;
                    //设置原图
                    setPlayer();
                    ToastUtils.showShort(getString(R.string.add_filter_suc));

                } else {
                    //添加滤镜
                    addFilter(filter);
                }
                break;
            case R.id.tvDeriveVideo:
                saveVideo();
                break;
        }
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        oldPath = videoPath;
        //设置播放器
        setPlayer();
        List<FilterBean> listFilter = new ArrayList<>();
        listFilter.add(new FilterBean(R.drawable.iv_filter1, "", "原图", "#00000000", true));
        listFilter.add(new FilterBean(R.drawable.iv_filter2, "lutyuv='u=128:v=128'", "素描", "#323333", false));
        listFilter.add(new FilterBean(R.drawable.iv_filter8, "hue='h=60:s=-3'", "鲜明", "#C376F3", false));
        listFilter.add(new FilterBean(R.drawable.iv_filter5, "lutyuv='y=maxval+minval-val:u=maxval+minval-val:v=maxval+minval-val'", "底片", "#6F7171", false));
        listFilter.add(new FilterBean(R.drawable.iv_filter10, "lutyuv=y=negval", "亮度负片", "#505151", false));
        listFilter.add(new FilterBean(R.drawable.iv_filter11, "lutyuv='u=128:v=128'", "灰度", "#999999", false));
        listFilter.add(new FilterBean(R.drawable.iv_filter12, "lutyuv='y=2*val'", "亮度燃烧", "#513232", false));
        listFilter.add(new FilterBean(R.drawable.iv_filter4, "unsharp", "锐化", "#787A7A", false));
        mDataBinding.rvFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new FilterAdapter();
        filterAdapter.setList(listFilter);
        mDataBinding.rvFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        filterAdapter.getItem(oldPosition).setSelect(false);
        filterAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        filterAdapter.getItem(position).setSelect(true);
        filterAdapter.notifyItemChanged(position);
        //设置滤镜
        if (isFilter) return;
        filter = filterAdapter.getItem(position).getFilter();
        isFilter = true;
        mDataBinding.rvFilterList.setEnabled(false);
        //重复路径 避免叠加
        videoPath = oldPath;
    }

    //添加滤镜
    private void addFilter(String filter) {
        EpVideo epVideo = new EpVideo(videoPath);
        epVideo.addFilter(filter);
        String path = FileUtil.generateFilePath(Content.myTemp, ".mp4", videoPath);
        EpEditor.OutputOption outputOption = new EpEditor.OutputOption(path);
        EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = false;
                        videoPath = path;
                        ToastUtils.showShort(getString(R.string.add_filter_suc));
                        //设置播放器
                        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                        mDataBinding.videoView.setVideoPath(videoPath);
                        mDataBinding.videoView.seekTo(1);
                        mDataBinding.videoView.start();
                        startTime();
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = false;
                        ToastUtils.showShort(R.string.set_filter_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                float v = progress * 100;
                if (v < 0) {
                    v = 0;
                } else if (v > 100) {
                    v = 100;
                }
                showDialog(getString(R.string.add_filter_ing) + new DecimalFormat("#.0").format(v) + getString(R.string.unit_percent));
            }
        });
    }

    //临时保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到相册
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        },500);
                    }
                });
            }
        }, 1000);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvVideoSbLeft.setText("00:00");
        mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoSbLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

}